<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
class Detail extends Controller
{  
   //详情页面
	public function index($id)
	{  
       $message=Db::name('message m')
          ->join('user u','m.uid=u.id')
          ->where('m.id',$id)
          ->field(['uname','email','tel','mname','des','m.create_time'=>'create_time','m.status'=>'status','m.id'=>'id','uid','image'])
          ->find();
       $judge=model('judge')->getAllById($id);
	   return view('',[
	   	'message'=>$message,
        'judge'=>$judge,
        'id'=>$id,
        'uid'=>$message['uid']
	   ]);
	}

    //对message点赞
    public function zan($id)
    {
       $res=Db::name('judge')->where('id',$id)->setInc('zan');
       if($res){
       	 return 1;
       }else{
       	 return 0;
       }
    }
    //取消点赞
    public function dzan($id)
    {
       $res=Db::name('judge')->where('id',$id)->setDec('zan');
       if($res){
       	 return 1;
       }else{
       	 return 0;
       }
    }
   //对message添加评论
   public function judge($id,$uid,$content)
   {
      $data['mid']=$id;
      $data['uid']=$uid;
      $data['content']=$content;
      $data['jid']=cookie('user')['id'];
      if(!cookie('user')){
          return 0;
      }
      $res=model('judge')->save($data);
      if($res){
      	return 1;
      }else{
      	return 0;
      }
   } 
  
  //下订单
	public function dingdan($mid,$xid)
	{
    $m=Db::name('message')->where('id',$mid)->find();
	  if(cookie('user')&&($m['status']==0)){
        $data['mid']=$mid;
        $data['xid']=$xid;
        $data['yid']=cookie('user')['id'];
        $user=Db::name('user')->where('id',$xid)->find();
        Db::startTrans();
        $res1=model('hand')->save($data);
        $res2=model('message')->save(['status'=>1],['id'=>$mid]);
        $message="您的订单已经被{$user['uname']}匹配，他的tel是{$user['tel']},请尽快联系他！！！";
        $res3=\phpmailer\Email::send($user['email'],"订单通知",$message);
        if($res1&&$res2&&$res3){
          Db::commit();
          return $this->success('下订单成功');
        }else{
          Db::rollback();
          return $this->error('下订单失败');
        }
    }elseif($m['status']==1){
      return $this->error('该订单已经匹配');
    }else{
      return $this->success('登陆后才能下订单,请先登录','index/login');
    }
	}
  

  //取消订单
  public function cancel()
  { 
    Db::startTrans();
    $data=input('post.');
    $res1=Db::name('hand')->where('id',$data['hid'])->delete();
    $res2=model('message')->save(['status'=>0],['id'=>$data['mid']]);
    if($res1&&$res2){
      $message="非常遗憾的告诉你，你的订单被取消了，对方的理由是：{$data['reason']}"; 
      $m=Db::name('message m')->join('user u','m.uid=u.id')->where('m.id',$data['mid'])->find();
      $res3=$res3=\phpmailer\Email::send($m['email'],"订单通知",$message);
      if($res1&&$res2&&$res3){
       return $this->success('该订单已经取消');
      }else{
       return $this->error('取消失败');
      }
    }else{
       return $this->error('取消失败');
    }
    
  }
}